"use strict";

import Vue from 'vue';
import axios from "axios";
import {getToken, removeLoginInfo} from "../utils/session_storage"
// import store from '@/store'
import { MessageBox, Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/ttxs";

let downloadLoadingInstance;

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    const token = getToken()
    if(token) {
        config.headers['Authorization'] = 'Bearer ' + token;
        config.headers['token'] = token;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
      let data = response.data;
      if(data.code == 200 || data.code == 0) {
          return Promise.resolve(data)
      } else if(data.code == 500) {
          MessageBox({message: data.msg, title:'错误', type:'warning'})
          return Promise.reject(data);
      } else if(response.headers['content-type'].search('octet-stream') > -1
                || response.headers['content-type'].search('application/vnd') > -1) {
          return Promise.resolve(data);
      } else {
          console.error('响应没有传递code，进入异常处理', data)
          return Promise.reject(data);
      }
  },
  function(error) {
      console.log(error);
      // Do something with response error
      if (error.response.status == 401) {
          MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                  confirmButtonText: '重新登录',
                  cancelButtonText: '取消',
                  type: 'warning'
              }
          ).then(() => {
              removeLoginInfo()
              location.href = '/index';
          })
      } else if(error.response.status == 403) {
          MessageBox({message:'当前用户无权访问此功能！请联系管理员',title:'警告', type:'warning'})
      } else if(error.response.status == 500 && error.response.data) {
          MessageBox({message: error.response.data.msg?error.response.data.msg:error.response.data, title:'提示', type:'warning'})
      } else if(error.response.status == 503 && error.response.data) {
          MessageBox({message: error.response.data.msg?error.response.data.msg:error.response.data, title:'提示', type:'warning'})
      }
      return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  if(!options) options = {}
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

// 通用下载方法
export function download(url, params, filename) {
    downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return _axios.post(url, params, {
        transformRequest: [(params) => { return tansParams(params) }],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob'
    }).then(async (data) => {
        console.log('then...')
        const isLogin = await blobValidate(data);
        if (isLogin) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
    })
}

Vue.use(Plugin)

export default Plugin;
export {_axios as request}
